package com.jdcjk.project.main.view.gaode;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.jdcjk.Constant;
import com.jdcjk.R;
import com.jdcjk.UrlAddress;
import com.jdcjk.base.presenter.BasePresenter;
import com.jdcjk.base.view.BaseFragment;
import com.jdcjk.chat.enity.MessageBean;
import com.jdcjk.project.car.view.CarActivity;
import com.jdcjk.project.car.view.TerminalDetailsActivity;
import com.jdcjk.project.main.model.entity.CarListInfo;
import com.jdcjk.project.main.model.entity.TerminalInfoListResult;
import com.jdcjk.project.main.presenter.MainPresenter;
import com.jdcjk.util.GaoDeMapUtil;
import com.jdcjk.util.PreferencesUtils;
import com.jdcjk.view.LoadingDialog;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

import static com.jdcjk.Constant.UserInfo.account;

/**
 * Created by dong on 2016/12/9.
 * 多车监控
 */
public class GDCarMonitorFragment extends BaseFragment<MainPresenter> implements AMap.InfoWindowAdapter {
    private final String TAG = GDCarMonitorFragment.class.getSimpleName();
    private AMap aMap;
    private ImageView mapType_imageView;
    private boolean isTouch = false;
    private SparseArray<Marker> carMarkerArray;
    private SparseArray<LatLng> carLatLngArray;
    private int currentIndex = 1000;
    //车辆信息List
    private List<CarListInfo> carInfoList = new ArrayList<>();
    //车辆位置刷新button
    ImageButton carInfoRefresh_button;
    //加载dialog
    private LoadingDialog loadingDialog;
    //地图放大等级
    private float zoomLevel = 16;

    //车辆信息窗口显示等级（0为不显示，1为小窗口，只显示名字，2位大窗口，显示车辆状态，acc等信息）
    private int carWindowsLevel = 1;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_gaode_car_monitor;
    }

    @Override
    public MainPresenter bindPresenter() {
        presenter = new MainPresenter(getContext());
        return presenter;
    }

    @Override
    public void initContentView(View viewContent) {
        initMap();
        initView();
    }

    private void initView() {
        mapType_imageView = (ImageView) viewContent.findViewById(R.id.fragment_car_monitor_map_type);
        mapType_imageView.setOnClickListener(this);
        viewContent.findViewById(R.id.fragment_car_monitor_previous).setOnClickListener(this);
        viewContent.findViewById(R.id.fragment_car_monitor_next).setOnClickListener(this);
        carInfoRefresh_button = (ImageButton) viewContent.findViewById(R.id.car_info_refresh_btn);
        carInfoRefresh_button.setOnClickListener(this);
        carMarkerArray = new SparseArray<>();
        carLatLngArray = new SparseArray<>();
        LatLng latLng;
        // 设置自定义窗口
        aMap.setInfoWindowAdapter(this);
        //判断车辆数是否为0
        if (carInfoList == null || carInfoList.size() == 0) {
            Toast.makeText(getActivity(), R.string.no_find_monitor_car, Toast.LENGTH_SHORT).show();
            return;
        }
        for (int i = 0; i < carInfoList.size(); i++) {
            latLng = new LatLng(carInfoList.get(i).getLatitude(), carInfoList.get(i).getLongitude());
            // 添加标注物
            Marker marker = addCarMarker(latLng, carInfoList.get(i));
            carMarkerArray.put(i, marker);
            carLatLngArray.put(i, latLng);
        }
        //移动到第一台车的位置
        latLng = new LatLng(carInfoList.get(0).getLatitude(), carInfoList.get(0).getLongitude());
        carMarkerArray.get(0).showInfoWindow();
        animateToLocation(latLng);
        // 设置初始值
        currentIndex *= carLatLngArray.size();
        //初始化加载dialog
        loadingDialog = new LoadingDialog(getActivity(), R.style.dialogTheme);
    }

    public void setCarList(List<CarListInfo> carInfoList) {
        this.carInfoList = carInfoList;
        //坐标转换
        for (int i = 0; i < carInfoList.size(); i++) {
            LatLng latLng = new LatLng(carInfoList.get(i).getLatitude(), carInfoList.get(i).getLongitude());
            latLng = GaoDeMapUtil.gaodeLatLngEncrypt(latLng);
            carInfoList.get(i).setLatLng(latLng.latitude, latLng.longitude);
        }
    }


    private void initMap() {
        //初始化地图变量
        if (aMap == null) {
            aMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_car_monitor_map)).getMap();
        }
        //定义了当可视范围改变时回调的接口。
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                //在可视范围改变完成之后回调此方法。
                zoomLevel = cameraPosition.zoom;
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                //在可视范围一系列动作改变完成之后（例如拖动、fling、缩放）回调此方法。
            }
        });
    }


    public void animateToLocation(LatLng latLng) {
        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                new LatLng(latLng.latitude, latLng.longitude),//新的中心点坐标
                zoomLevel, //新的缩放级别
                0, //俯仰角0°~45°（垂直与地图时为0）
                0  ////偏航角 0~360° (正北方为0)
        )));
    }

    /**
     * 在对应位置添加车辆标志物
     *
     * @param latLng      位置信息
     * @param carListInfo 车辆信息
     * @return
     */
    private Marker addCarMarker(LatLng latLng, CarListInfo carListInfo) {
        // 创建标注物
        MarkerOptions markerOption = new MarkerOptions();
        // 设置地点位置（经纬度）
        markerOption.position(latLng);
        // 设置标注物的标题和描述--坑爹，必须设置
        markerOption.title(carListInfo.getDisplayid()).snippet(carListInfo.getCardNum());
        // 设置标注物是否可以拖拽（长按拖拽）
        markerOption.draggable(true);
        // 设置标注物的自定义图标
        if (carListInfo.getOnline()) {
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), carListInfo.getDirection() > 180 ? R.mipmap.motorcycle_left_online : R.mipmap.motorcycle_right_online)));//摩托车图标
        } else {
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), carListInfo.getDirection() > 180 ? R.mipmap.motorcycle_left_offline : R.mipmap.motorcycle_right_offline)));//摩托车图标
        }
        // 添加标注物至地图显示
        final Marker marker = aMap.addMarker(markerOption);
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (!isTouch) {
                    if (marker.isInfoWindowShown()) {
                        //判断显示的窗口等级，如果为大窗口等级，则不显示窗口
                        switch (carWindowsLevel) {
                            case 1:
                                carWindowsLevel = 2;
                                marker.showInfoWindow();
                                break;
                            case 2:
                                marker.hideInfoWindow();
                                carWindowsLevel = 0;
                                break;
                        }
                    } else {
                        carWindowsLevel = 1;
                        marker.showInfoWindow();
                    }
                }
                return true;
            }
        });
        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent event) {
                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        if (marker.isInfoWindowShown()) {
//                            marker.hideInfoWindow();
//                            isTouch = true;
//                        } else {
//                            isTouch = false;
//                        }
//                        break;
                }
            }
        });
        return marker;
    }

    //当前车辆标志
    private int carPostion = 0;

    @Override
    public View getInfoWindow(Marker marker) {
        //判断当前为第几个标志物
        for (int i = 0; i < carMarkerArray.size(); i = i + 1) {
            if (carMarkerArray.get(i).equals(marker)) {
                carPostion = i;
                break;
            }
        }
        //判断弹出窗口等级
        if (carWindowsLevel == 1) {
            View infoWindow = getActivity().getLayoutInflater().inflate(R.layout.dialog_info_window_gaode_level_one, null);
            //设备名称textView
            TextView name_textView = (TextView) infoWindow.findViewById(R.id.dialog_info_window_car_displayid);
            //车牌号textview
            TextView carCardId_textview = (TextView) infoWindow.findViewById(R.id.dialog_info_window_car_card_id_tv);
            //车辆状态textview
            TextView carOnlineStatus_textview = (TextView) infoWindow.findViewById(R.id.dialog_info_window_online_status_tv);
            name_textView.setText(carInfoList.get(carPostion).getDisplayid());
            carCardId_textview.setText(carInfoList.get(carPostion).getCarId());
            carOnlineStatus_textview.setText(carInfoList.get(carPostion).getOnline() ? "在线" : "离线");
            //窗口点击监听，显示车辆详细信息窗口
            infoWindow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    carWindowsLevel = 2;
                    carMarkerArray.get(carPostion).showInfoWindow();
                }
            });
            return infoWindow;
        }
        View infoWindow = getActivity().getLayoutInflater().inflate(R.layout.dialog_info_window_gaode, null);
        //设备名称textView
        TextView name_textView = (TextView) infoWindow.findViewById(R.id.dialog_info_window_name_tv);
        //车辆状态textview
        TextView carStatus_textview = (TextView) infoWindow.findViewById(R.id.dialog_info_window_car_status);
        //车辆速度LinearLayout
        LinearLayout speed_lingearLayout = (LinearLayout) infoWindow.findViewById(R.id.dialog_info_window_speed_ll);
        //速度textView
        TextView speed_textView = (TextView) infoWindow.findViewById(R.id.dialog_info_window_speed_tv);
        //ACC状态textView
        TextView accStatus_textView = (TextView) infoWindow.findViewById(R.id.dialog_info_window_acc_status_tv);
        //通信时间textView
        TextView communicationTime_textView = (TextView) infoWindow.findViewById(R.id.dialog_info_window_communication_time_tv);
        //定位时间textView
        TextView loactionTime_textView = (TextView) infoWindow.findViewById(R.id.dialog_info_window_loaction_time_tv);
        //是否在线textView
        TextView onlineStatus_textView = (TextView) infoWindow.findViewById(R.id.dialog_info_window_online_status);
        //设备详情button
        ImageButton carTerminalSetBtn = (ImageButton) infoWindow.findViewById(R.id.terminal_set_btn);
        carTerminalSetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TerminalDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.TerminalInfo.terminalId, carInfoList.get(carPostion).getId());
                bundle.putString(Constant.FragmentInfo.fragment, Constant.FragmentInfo.mainActivity);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }
        });
        name_textView.setText(carInfoList.get(carPostion).getDisplayid());
        //判断速度大小，若速度为0，则设置车辆状态为静止，不显示速度布局，否则显示为运动，显示车辆速度布局
        if (carInfoList.get(carPostion).getSpeed() == 0) {
            speed_lingearLayout.setVisibility(View.GONE);
            carStatus_textview.setText(R.string.motionless);
        } else {
            speed_lingearLayout.setVisibility(View.VISIBLE);
            String speed = carInfoList.get(carPostion).getSpeed() + getResources().getString(R.string.km_h);
            speed_textView.setText(speed);
            carStatus_textview.setText(R.string.movement);
        }
        communicationTime_textView.setText(carInfoList.get(carPostion).getUpdatedTime());
        loactionTime_textView.setText(carInfoList.get(carPostion).getLocationTime());
        accStatus_textView.setText(carInfoList.get(carPostion).getAcc() ? "开" : "关");
        onlineStatus_textView.setText(carInfoList.get(carPostion).getOnline() ? "在线" : "离线");
        onlineStatus_textView.setTextColor(getResources().getColor(carInfoList.get(carPostion).getOnline() ? R.color.green : R.color.orange));
        //弹窗信息布局点击监听
        infoWindow.findViewById(R.id.dialog_info_window_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到单个设备界面
                Intent intent = new Intent(getActivity(), CarActivity.class);
                intent.putExtra(Constant.TerminalInfo.terminalId, carInfoList.get(carPostion).getId());
                startActivity(intent);
            }
        });
        return infoWindow;
    }

    public void updataCarListInfo(String displayid, String carId, String cardNum) {
        carInfoList.get(carPostion).setDisplayid(displayid);
        carInfoList.get(carPostion).setCarId(carId);
        carInfoList.get(carPostion).setCardNum(cardNum);
        //刷新弹窗
        carMarkerArray.get(carPostion).showInfoWindow();
    }

    public void updataCarInfo(final MessageBean.TerminalStatusBean terminalStatusBean) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < carInfoList.size(); i++) {
                    //判断状态变化的车辆id
                    if (terminalStatusBean.getId() == carInfoList.get(i).getId()) {
                        //刷新车辆的数据，并刷新显示
                        carInfoList.get(i).setOnline(terminalStatusBean.isOnline());
                        carInfoList.get(i).setDisplayid(terminalStatusBean.getDisplayid());
                        carInfoList.get(i).setAcc(terminalStatusBean.isAcc());
                        carInfoList.get(i).setLatitude(terminalStatusBean.getLatitude());
                        carInfoList.get(i).setLongitude(terminalStatusBean.getLongitude());
                        Message msg = new Message();
                        //存储当前信息被修改的车辆在List中的位置
                        msg.arg1 = i;
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                int i = msg.arg1;
                //刷新当前list
                LatLng latLng = new LatLng(carInfoList.get(i).getLatitude(), carInfoList.get(i).getLongitude());
                //坐标转换
                latLng = GaoDeMapUtil.gaodeLatLngEncrypt(latLng);
                //移除同一车辆的标注
                carMarkerArray.get(i).remove();
                // 添加该车辆新的标注物
                Marker marker = addCarMarker(latLng, carInfoList.get(i));
                carMarkerArray.put(i, marker);
                carLatLngArray.put(i, latLng);
            }
        }
    };

    public void refreshCarInfo() {
        // 获取数据
        account = PreferencesUtils.getString(getActivity(), account);
        //获取用户设备列表
        presenter.getTerminalForUser(UrlAddress.GET_TERMINAL_FOR_USER, account, new BasePresenter.OnUIThreadListener<TerminalInfoListResult>() {
            @Override
            public void onBefore(Request request, int id) {
                loadingDialog.show();
                loadingDialog.setTextView(R.string.is_loaction);
            }

            @Override
            public void onAfter(int id) {
            }

            @Override
            public void onError(Call call, Exception e, int i) {
                loadingDialog.dismiss();
                Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(TerminalInfoListResult result) {
                switch (result.getStatus()) {
                    case "OK":
                        //终端列表信息
                        carInfoList = result.getResult();
                        LatLng latLng;
                        //判断车辆数是否为0
                        if (carInfoList == null || carInfoList.size() == 0) {
                            Toast.makeText(getActivity(), R.string.no_find_monitor_car, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //清除之前的标志物
                        aMap.clear();
                        for (int i = 0; i < carInfoList.size(); i++) {
                            latLng = new LatLng(carInfoList.get(i).getLatitude(), carInfoList.get(i).getLongitude());
                            //坐标转换
                            latLng = GaoDeMapUtil.gaodeLatLngEncrypt(latLng);
                            carInfoList.get(i).setLatLng(latLng.latitude, latLng.longitude);
                            // 添加标注物
                            Marker marker = addCarMarker(latLng, carInfoList.get(i));
                            carMarkerArray.put(i, marker);
                            carLatLngArray.put(i, latLng);
                        }
                        //移动到第一台车的位置
                        latLng = new LatLng(carInfoList.get(0).getLatitude(), carInfoList.get(0).getLongitude());
                        //显示弹窗
                        carWindowsLevel = 1;
                        carMarkerArray.get(0).showInfoWindow();
                        animateToLocation(latLng);
                        // 设置初始值
                        currentIndex *= carLatLngArray.size();
                        break;
                    case "FAILED":
                        break;
                }
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * 关闭当前所有设备
     */
    public void closeAllTerminal() {
        for (int i = 0; i < carInfoList.size(); i++) {
            //刷新车辆的数据，并刷新显示
            carInfoList.get(i).setOnline(false);
            carInfoList.get(i).setAcc(false);
            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
        }
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    public AMap getAMap() {
        return aMap;
    }

    public ImageView getMapTypeImageView() {
        return mapType_imageView;
    }

    public SparseArray<Marker> getCarMarkerArray() {
        return carMarkerArray;
    }

    public SparseArray<LatLng> getCarLatLngArray() {
        return carLatLngArray;
    }

    public int getCurrentIndex() {
        return currentIndex;
    }

    public void setCurrentIndex(int currentIndex) {
        this.currentIndex = currentIndex;
    }

    public int getCarWindowsLevel() {
        return carWindowsLevel;
    }

    public void setCarWindowsLevel(int carWindowsLevel) {
        this.carWindowsLevel = carWindowsLevel;
    }
}
